<script setup>
import {ref, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {getArticleByKeyword, getAllArticle,addFavArticle,getArticelDetail} from "@/apis/article";
import {ElMessage} from "element-plus";

const article = ref([])
const router = useRouter();
const keyword = router.currentRoute.value.query.keyword

const getArticles = async () => {
  await getAllArticle().then(res => {
    article.value = res.data
  })

}
const getArticleByKey = async (keyword) => {
  const res = await getArticleByKeyword(keyword)
  article.value = res.data
  if (res.code == 200) {
    ElMessage({type: 'success', message: res.message})
  } else if (res.code == 505) {
    ElMessage({type: 'error', message: res.message})
    getArticles()
  } else {
    ElMessage({type: 'error', message: res.message})
    getArticles()
  }
}
onMounted(() => {
  getArticleByKey(keyword)
})
//收藏
const collect = async (articleid)=>{
  const res =await addFavArticle(articleid)
  console.log(res)
  if(res.code == 200){
    ElMessage({type:'success',message:res.message})
  }else{
    ElMessage({type:'error',message:res.message})
  }
}
//查看详情
const getDetails = async (articleid) => {
  const res = await getArticelDetail(articleid)
  if (res.code == 200) {
    router.push({path: '/detail',query:{articleid:articleid}})
  } else {
    ElMessage({type: 'warn', message: '你所访问的文章已经被删除'})
  }
}
</script>
<template>
  <div class="article">
    <el-card class="box-card" v-for="item in article" :key="item.id">
      <div class="cardmain">
        <div>文章名称:{{ item.title }}</div>
        <div>作者：{{ item.nickname }}</div>
        <div>点赞数量：{{ item.likes }}</div>
        <div style="margin: 5px 0;display: flex;flex-direction: row">
          <el-button type="primary" @click="getDetails(item.id)" style="width: 50%">查看详情</el-button>
          <el-button type="success" style="width: 20%" @click="collect(item.id)" v-if="true">收藏</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>
<style scoped>
.cardmain {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  text-align: left;
}

.box-card {
  width: 20%;
  height: 180px;
  margin: 50px;

}

.article {
  margin-left: 200px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
}

span {
  margin: 3px;
}
</style>